/*
 * File to form signIn requests
 * 
 * Author: Chris Casola
 */

/**
 * Form a valid sign in request
 */
function signInRequest(username, gameid) {
	this.__XMLclass = "signInRequest";
	this.id = gameid;
	this.__XMLchildren = [
		{__XMLclass : "user", name : username}	
	];
}

/**
 * Process a signIn response
 */
function handleSignInResponse(response) {
	if (response.success == "false")
		return; /* error */
		
	var signInResponse = response.signInResponse;
	
	// the event is closed
	if (signInResponse.type == "closed") {
		window.dlEvent = new Event(parseInt(signInResponse.numChoices),	parseInt(signInResponse.numRounds));
		sessionStorage['gameid'] = signInResponse.id;
		window.dlEvent.eventType = "closed";
		window.dlEvent.question = signInResponse.question;
		window.dlEvent.playerPosition = parseInt(signInResponse.position);
		addEventChoices(signInResponse.choice);
		window.frame.changeForm("addEdge");
	}
	
	// the event is open
	else if (signInResponse.type == "open") {
		window.dlEvent = new Event(parseInt(signInResponse.numChoices),	parseInt(signInResponse.numRounds));
		sessionStorage['gameid'] = signInResponse.id;
		window.dlEvent.eventType = "open";
		window.dlEvent.question = signInResponse.question;
		window.dlEvent.playerPosition = parseInt(signInResponse.position);
		addEventChoices(signInResponse.choice);
		window.frame.changeForm("addChoice");
	}
}

/**
 * Adds the choices contained in the signIn response to the local
 * event model and display them on the page
 */
function addEventChoices(choices) {
	if (typeof(choices) != "undefined") {
		if (Array.isArray(choices)) {
			for (var i=0; i<choices.length; i++) {
				window.dlEvent.setChoiceLabel(choices[i].value, choices[i].index);
				var choiceList = document.getElementById('choiceList');
				var newChoiceLi = document.createElement('li');
				newChoiceLi.innerHTML = choices[i].value;
				choiceList.appendChild(newChoiceLi);
			}
		}
		else {
			window.dlEvent.setChoiceLabel(choices.value, choices.index);
			var choiceList = document.getElementById('choiceList');
			var newChoiceLi = document.createElement('li');
			newChoiceLi.innerHTML = choices.value;
			choiceList.appendChild(newChoiceLi);
		}
	}
}
